<?php

namespace app\web\controller;

use app\common\util\ErrorCode;
use app\web\service\LoginService;
use think\App;

class CommonController
{
    public $noCheckTokenAction = []; //不校验token的方法名
    public $returnData = [];
    protected $app;
    public $params;

    public function __construct(App $app = null)
    {
        if(request()->method() == "OPTIONS"){
            $this->returnData = ErrorCode::code('fail');
            return false;
        }
        $this->app = $app; // 应用对象
        $this->params = request()->param();
        $this->initialize();
        //处理登录token等信息
        if(!in_array(request()->action(true), $this->noCheckTokenAction)){
            if(!empty($this->params['token'])) { //就校验token是否有效或者过期
                if (!$userLoginData = $this->getTokenVar($this->params["token"])) {
                    return false;
                }
                $this->app->request->userLoginData = $userLoginData; // 把信息存到request对象里，全局可以调用
            }else{
                $this->returnData = ErrorCode::code('token_expire');
                $this->returnData["msg"] = "token参数不存在";
                return false;
            }
        }
        return true;
    }

    public function initialize()
    {
        $this->returnData = ErrorCode::code("success");
    }

    public function getTokenVar($token, $key = '')
    {
        $data = LoginService::checkToken($token);
        if(isset($data["code"])){
            $this->returnData = $data;
            return false;
        }
        if(empty($key)){
            return $data;
        }
        if (array_key_exists($key, $data)) {
            return $data[$key];
        }else{
            return "";
        }
    }

    public function return_result($data, $text = '')
    {
        if(!is_array($data['msg']) && $text && strpos($data['msg'], "%s") !== false){
            $data['msg'] = sprintf($data['msg'], $text);
        }
        $this->app->db()->getConnection()->close(); // 关闭数据库连接
        return json($data);
    }

    //空操作
    public function _empty()
    {
        return $this->return_result(ErrorCode::$errorCode['method_not_exist']);
    }
}
